﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace JHMVVMFramework.Common.Command
{
    public class DelegateCommand<CommandArgType> :ICommand
    {
        private Action<CommandArgType> m_executeAction;
        private Func<CommandArgType, bool> m_canExecuteFunc;

        private bool m_isCanExecute = true;
        public bool IsCanExecute
        {
            get { return m_isCanExecute; }
            set 
            {
                if (value != m_isCanExecute)
                {
                    m_isCanExecute = value;
                    FireCanExecuteChanged();
                }
            }
        }

        public event EventHandler CanExecuteChanged;

        public DelegateCommand(Action<CommandArgType> executeAction)
        {
            m_executeAction = executeAction;
        }

        public DelegateCommand(Action<CommandArgType> executeAction, Func<CommandArgType, bool> canExecuteAction)
        {
            m_executeAction = executeAction;
            m_canExecuteFunc = canExecuteAction;
        }

        private void FireCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
                CanExecuteChanged(this, new EventArgs());
        }

        public bool CanExecute(object parameter)
        {
            if (m_canExecuteFunc == null)
            {
                return IsCanExecute;
            }
            else
            {
                CommandArgType args = (CommandArgType)parameter;

                IsCanExecute = m_canExecuteFunc(args);
            }
            return IsCanExecute;
        }

        public void Execute(object parameter)
        {
            if (m_executeAction != null)
            {
                CommandArgType args = (CommandArgType)parameter;
                m_executeAction(args);
            }
        }
    }
}
